<template>
	<app-page>
		<wd-config-provider :theme="theme">
			<view class="container">
				<view class="form">
					<wd-form ref="formRef" :model="formData" :rules="formRules">
						<view class="form-item">
							<wd-datetime-picker prop="startDate" type="date" v-model="formData.startDate"
								label="开始时间" />
						</view>
						<view class="form-item">
							<wd-datetime-picker prop="endDate" type="date" v-model="formData.endDate" label="结束时间" />
						</view>

						<view class="form-item">
							<wd-cell required title="本金" vertical>
								<wd-input v-model="formData.loanAmount" prop="loanAmount" placeholder="本金" />
							</wd-cell>
						</view>

						<view class="form-item">
							<wd-cell vertical title="自然年天数基准">
								<wd-picker v-model="formData.naturalDays" :columns="naturalDaysColumns" />
							</wd-cell>

						</view>
						<view class="form-item">
							<wd-cell vertical title="利率模式">
								<wd-picker v-model="formData.interestRate" :columns="interestRateColumns" />
							</wd-cell>

						</view>
						<view class="form-item" v-if="formData.interestRate === '一年利率'">
							<wd-cell title="法定最高4倍1年期LPR" vertical>
								<wd-radio-group shape="dot" v-model="formData.multiple">
									<wd-radio :value="true">开启</wd-radio>
									<wd-radio :value="false">关闭</wd-radio>
								</wd-radio-group>
							</wd-cell>
						</view>

					</wd-form>
				</view>
				<view class="footer">
					<wd-button @click="calculate" type="success"
						custom-class="wd-button-custom-class-my-success square wd-button-custom-class-w100">
						计算
					</wd-button>
				</view>
				<view class="tips">
					<view>
						计算公式：
					</view>
					<view>总还款月数 = 结束时间 - 开始时间</view>
					<view>每期需要还款本金 = 本金 / 总还款月数</view>
					<view>
						2020年08月20日前
					</view>
					<view>
						每期利息 = 剩余还款本金 * 24% * 本期天数 / 自然年天数基准
					</view>
					<view>2020年08月20日后</view>
					<view>
						每期利息 = 剩余还款本金 * 本期利率(根据选择 使用 1年期LPR、5年期LPR或者1年期LPR*4) * 本期天数 / 自然年天数基准
					</view>
					<view>
						本期还款金额 = 每期需要还款本金 + 每期利息
					</view>
				</view>

			</view>
		</wd-config-provider>
	</app-page>
</template>

<script lang="ts">
	import { defineComponent, reactive, ref } from 'vue';

	import { onPageScroll, onLoad } from '@dcloudio/uni-app';
	import useRouter from '@/hooks/useRouter';
	import { getLprList } from "@/api/index"


	export default defineComponent({
		name: '',
		components: {},
		setup(props, ctx) {
			// 日间light、夜间dark主题
			const theme = ref('light');
			const router = useRouter();
			const formRef = ref();
			const naturalDaysColumns = ref([['365', '360']])
			const interestRateColumns = ref([['一年利率', '五年利率']])
			const formData = reactive({
				startDate: "",
				endDate: "",
				loanAmount: "",
				naturalDays: '360',
				interestRate: "一年利率",
				multiple: false,

			})
			const formRules = reactive({
				startDate: [
					{ required: true, message: '请选择开始时间', trigger: 'blur' }
				],
				endDate: [
					{ required: true, message: '请选择截至时间', trigger: 'blur' }
				],
				loanAmount: [
					{ required: true, message: '请输入贷款金额', trigger: 'blur' }
				],

			})
			// lpr 利率
			const lprList = ref([
				{
					"date": "2019-08-20",
					"a_year": "4.25%",
					"five_year": "4.85%"
				},
				{
					"date": "2019-09-20",
					"a_year": "4.20%",
					"five_year": "4.85%"
				},
				{
					"date": "2019-10-21",
					"a_year": "4.20%",
					"five_year": "4.85%"
				},
				{
					"date": "2019-11-20",
					"a_year": "4.15%",
					"five_year": "4.80%"
				},
				{
					"date": "2019-12-20",
					"a_year": "4.15%",
					"five_year": "4.80%"
				},
				{
					"date": "2020-01-20",
					"a_year": "4.15%",
					"five_year": "4.80%"
				},
				{
					"date": "2020-02-20",
					"a_year": "4.05%",
					"five_year": "4.75%"
				},
				{
					"date": "2020-03-20",
					"a_year": "4.05%",
					"five_year": "4.75%"
				},
				{
					"date": "2020-04-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-05-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-06-22",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-07-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-08-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-09-21",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-10-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-11-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2020-12-21",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-01-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-02-22",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-03-22",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-04-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-05-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-06-21",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-07-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-08-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-09-22",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-10-20",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-11-22",
					"a_year": "3.85%",
					"five_year": "4.65%"
				},
				{
					"date": "2021-12-20",
					"a_year": "3.80%",
					"five_year": "4.65%"
				},
				{
					"date": "2022-01-20",
					"a_year": "3.70%",
					"five_year": "4.60%"
				},
				{
					"date": "2022-02-21",
					"a_year": "3.70%",
					"five_year": "4.60%"
				},
				{
					"date": "2022-03-21",
					"a_year": "3.70%",
					"five_year": "4.60%"
				},
				{
					"date": "2022-04-20",
					"a_year": "3.70%",
					"five_year": "4.60%"
				},
				{
					"date": "2022-05-20",
					"a_year": "3.70%",
					"five_year": "4.45%"
				},
				{
					"date": "2022-06-20",
					"a_year": "3.70%",
					"five_year": "4.45%"
				},
				{
					"date": "2022-07-20",
					"a_year": "3.70%",
					"five_year": "4.45%"
				},
				{
					"date": "2022-08-22",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2022-09-20",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2022-10-20",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2022-11-21",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2022-12-20",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2023-01-20",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2023-02-20",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2023-03-20",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2023-04-20",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2023-05-22",
					"a_year": "3.65%",
					"five_year": "4.30%"
				},
				{
					"date": "2023-06-20",
					"a_year": "3.55%",
					"five_year": "4.20%"
				},
				{
					"date": "2023-07-20",
					"a_year": "3.55%",
					"five_year": "4.20%"
				},
				{
					"date": "2023-08-21",
					"a_year": "3.45%",
					"five_year": "4.20%"
				},
				{
					"date": "2023-09-20",
					"a_year": "3.45%",
					"five_year": "4.20%"
				},
				{
					"date": "2023-10-20",
					"a_year": "3.45%",
					"five_year": "4.20%"
				},
				{
					"date": "2023-11-20",
					"a_year": "3.45%",
					"five_year": "4.20%"
				},
				{
					"date": "2023-12-20",
					"a_year": "3.45%",
					"five_year": "4.20%"
				},
				{
					"date": "2024-01-22",
					"a_year": "3.45%",
					"five_year": "4.20%"
				},
				{
					"date": "2024-02-20",
					"a_year": "3.45%",
					"five_year": "3.95%"
				},
				{
					"date": "2024-03-20",
					"a_year": "3.45%",
					"five_year": "3.95%"
				},
				{
					"date": "2024-04-22",
					"a_year": "3.45%",
					"five_year": "3.95%"
				},
				{
					"date": "2024-05-20",
					"a_year": "3.45%",
					"five_year": "3.95%"
				},
				{
					"date": "2024-06-20",
					"a_year": "3.45%",
					"five_year": "3.95%"
				}
			])
			const monthDiff = (d1 : any, d2 : any) => {
				var months, dd1 = new Date(d1), dd2 = new Date(d2);
				months = (dd2.getFullYear() - dd1.getFullYear()) * 12;
				months -= dd1.getMonth();
				months += dd2.getMonth();
				if (dd1.getDate() !== dd2.getDate()) {
					months += 1
				}
				return months <= 0 ? 0 : months;
			}
			const dayDiff = (start : any, end : any) => {
				return (new Date(end).getTime() - new Date(start).getTime()) / 1000 / 60 / 60 / 24
			}
			const getDate = (str : any) => {
				let date = new Date(str),
					year = date.getFullYear(),
					month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1),
					day = date.getDate()
				return `${year}/${month}/${day}`
			}
			const calculate = () => {
				formRef.value.validate().then(({ err, valid }) => {
					if (valid) {
						uni.$wdToast.loading("计算中");
						const repaymentList = [];
						// 计算逻辑...
						let {
							startDate,
							endDate,
							loanAmount,
							naturalDays,
							interestRate,
							multiple
						} = JSON.parse(JSON.stringify(formData))
						let months = monthDiff(startDate, endDate)
						let monthLoanAmount = (Number(loanAmount) / months); // 计算每月贷款金额，假设贷款金额不变，实际需要根据贷款金额和月数计算
						console.log("monthLoanAmount", typeof monthLoanAmount, monthLoanAmount)
						// 遍历月数量 计算月份
						let all = 0;
						let oldMonths = monthDiff(startDate, '2020/08/20')
						console.log('oldMonths', oldMonths)

						if (oldMonths) {
							for (let i = 0; i < oldMonths; i++) {
								// 获取临时日期
								let tempStartDate = new Date(startDate);
								tempStartDate.setMonth(tempStartDate.getMonth() + i)
								let tempEndDate = new Date(startDate);
								// 如果是最后一个月 使用选择的结束日期
								if (i == months - 1) {
									tempEndDate = new Date(endDate);
								} else {
									// 计算结束日期，这里假设每个月的结束日期是下个月的开始日期，实际需要根据
									tempEndDate.setMonth(tempEndDate.getMonth() + (i + 1))
								}
								// 计算利息
								let days = dayDiff(tempStartDate, tempEndDate)
								// 计算利息 利率 * 贷款金额 * 天数 / 自然天数
								let interest = Number(loanAmount) * (parseFloat('24%') / 100) * days / Number(naturalDays);

								if (loanAmount < monthLoanAmount) {
									monthLoanAmount = loanAmount;
									loanAmount = 0;
								} else {
									loanAmount -= Number(monthLoanAmount); // 更新贷款金额，假设贷款金额不变，实际需要根据贷款金额和月数计算
								}
								console.log('该期利率24%')
								console.log('该期还本金 monthLoanAmount', monthLoanAmount)
								console.log('该期利息', interest.toFixed(2))
								console.log('该期还款', (Number(monthLoanAmount) + interest).toFixed(2))
								console.log('该期天数', days)
								console.log('剩余本金', loanAmount)
								all += (Number(monthLoanAmount) + interest)
								repaymentList.push({
									date: getDate(tempStartDate),
									endDate: getDate(tempEndDate),
									principal: Number(monthLoanAmount).toFixed(2), // 每月应还本金，假设贷款金额不变，实际需要根据贷款金额和月数计算
									interest: interest.toFixed(2), // 每月应还利息，实际需要根据贷款金额、利率和天数计算
									loanAmount: loanAmount <= 0 ? '0.00' : Number(loanAmount).toFixed(2),
									days,
									rate: '24%'
								})
							}
						}

						for (let i = 0; i < months - oldMonths; i++) {
							// 获取临时日期
							let tempStartDate = new Date('2020/08/20');
							tempStartDate.setMonth(tempStartDate.getMonth() + i)
							let tempEndDate = new Date('2020/08/20');
							// 如果是最后一个月 使用选择的结束日期
							if (i == months - 1) {
								tempEndDate = new Date(endDate);
							} else {
								// 计算结束日期，这里假设每个月的结束日期是下个月的开始日期，实际需要根据
								tempEndDate.setMonth(tempEndDate.getMonth() + (i + 1))
							}
							// 计算利息
							let days = dayDiff(tempStartDate, tempEndDate)
							// 获取最后一个月利率 
							let lastLpr = lprList.value[lprList.value.length - 1];
							// 利率排序日期大的在上面
							lprList.value = lprList.value.sort((a : any, b : any) => new Date(b.date).getTime() - new Date(a.date).getTime())
							// 获取利率
							let rate = null;
							for (let i = 0; i < lprList.value.length; i++) {
								var item = lprList.value[i];
								// 遍历循环 对比时间 获取利率
								if (tempStartDate >= new Date(item.date)) {
									rate = item;
									console.log(item, item.date, getDate(tempStartDate));
									break;
								}
							}
							// 如果没有利率 则使用最后一个月利率 计算利息 这里需要根据实际情况处理，比如使用平均利率等策略
							// && new Date(lastLpr.date) < new Date(tempStartDate)
							if (!rate) {
								rate = lastLpr
							}
							console.log(rate);
							// 计算利息 利率 * 贷款金额 * 天数 / 自然天数
							let rateNumber = (parseFloat(rate[interestRate == '一年利率' ? 'a_year' : 'five_year']) / 100)
							if (multiple) {
								rateNumber = rateNumber * 4
							}
							let interest = Number(loanAmount) * rateNumber * days / Number(naturalDays);

							console.log(getDate(tempStartDate), getDate(tempEndDate));

							if (loanAmount < monthLoanAmount) {
								monthLoanAmount = loanAmount;
								loanAmount = 0;
							} else {
								loanAmount -= Number(monthLoanAmount); // 更新贷款金额，假设贷款金额不变，实际需要根据贷款金额和月数计算
							}
							console.log('该期利率', rateNumber)
							console.log('该期还本金 monthLoanAmount', Number(monthLoanAmount))
							console.log('该期利息', interest.toFixed(2))
							console.log('该期还款', (Number(monthLoanAmount) + interest).toFixed(2))
							console.log('该期天数', days)
							console.log('剩余本金', loanAmount)
							all += (Number(monthLoanAmount) + interest)
							repaymentList.push({
								date: getDate(tempStartDate),
								endDate: getDate(tempEndDate),
								principal: Number(monthLoanAmount).toFixed(2), // 每月应还本金，假设贷款金额不变，实际需要根据贷款金额和月数计算
								interest: interest.toFixed(2), // 每月应还利息，实际需要根据贷款金额、利率和天数计算
								loanAmount: loanAmount <= 0 ? '0.00' : Number(loanAmount).toFixed(2),
								days,
								rate: (rateNumber * 100) + '%'
							})
						}
						uni.$wdToast.close();
						router.push({
							url: "/tools/loan/info",
							success: function (res) {
								// 通过eventChannel向被打开页面传送数据
								res.eventChannel.emit('sendData', {
									all: all.toFixed(2),
									interest: (Number(all) - Number(formData.loanAmount)).toFixed(2), // 总利息，实际需要根据贷款金额、利率和天数计算
									loanAmount: Number(formData.loanAmount).toFixed(2),
									repaymentList,
								})
							}
						})
						console.log('还款周期 months', months)
						console.log('总还款', all.toFixed(2))
						console.log('还款列表', repaymentList)
					}
				})

			}
			onLoad(() => {
				getLprList().then((res) => {
					console.log(res)
					lprList.value = res;
				})
			})
			return {
				theme,
				formData,
				formRules,
				formRef,
				calculate,
				naturalDaysColumns,
				interestRateColumns
			};
		}
	});
</script>
<!-- #ifdef MP-WEIXIN -->
<style lang="less">
	page {
		background-color: #f2f2f2;
	}
</style>
<!-- #endif -->
<style lang="less" scoped>
	.container {
		padding: 24rpx;
		background-color: #f2f2f2;

		.form {
			.checkbox {
				padding: 18rpx;
			}


			.form-item {
				padding: 18rpx !important;
				border-radius: 14rpx;
				overflow: hidden;

				:deep(.wd-textarea) {
					padding: 24rpx;
					border-radius: 14rpx;
				}

				:deep(.wd-input) {
					padding: 0 24rpx;
					border-radius: 14rpx;

					.wd-input__inner {
						height: 44px;
						line-height: 44px;
					}
				}

				:deep(.wd-radio-group) {
					padding: 0 24rpx 24rpx;
					border-radius: 14rpx;
					overflow: hidden;
				}

				:deep(.wd-radio.is-dot.is-checked .wd-radio__shape) {
					background-color: #c91c1f;
					border-color: #c91c1f;
				}

				:deep(.wd-cell) {
					background-color: transparent;
					padding-left: 0;

					.wd-cell__wrapper {
						padding-right: 0;
						padding: 0;
					}

					.wd-cell__right {
						margin-top: 20rpx;
					}

					.wd-cell__wrapper.is-vertical .wd-cell__value {
						max-width: 100%;
					}

					.wd-cell__body {
						// background-color: #FFF;
						border-radius: 14rpx;
						overflow: hidden;
					}
				}

			}
		}

		.tips {
			font-size: 30rpx;
			padding: 14rpx;
			color: #c91c1f;

			view {
				padding: 12rpx;
			}
		}

		.result {
			margin: 18rpx;
			width: calc(100% - 18rpx - 18rpx);
			overflow: hidden;
		}

		.footer {
			margin-top: 24rpx;
			padding: 18rpx;
		}
	}
</style>